<template>
    <el-container>
        <el-main class="wrapper art-update">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{'min-height': mainHeight+'px'}">
                <div class="panel-body">
                    <el-form :model="formData" label-position="top" :rules="rules" ref="formData" label-width="100px" class="demo-ruleForm">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item required prop="music_name">
                                    <el-input v-model="formData.music_name" placeholder="请填写音乐名称"></el-input>
                                </el-form-item>
                                <el-form-item required prop="music">
                                    <el-input v-model="formData.music" placeholder="请填写音乐编号"></el-input>
                                </el-form-item>
                                <el-form-item required class="background" prop="backimg">
                                    <el-popover
                                        placement="right"
                                        width="1000" v-model="backimgsShow"
                                        trigger="click">
                                        <el-row :gutter="20" class="backimgs">
                                            <el-col v-for="item in backimgs" :key="item.id" :span="6" style="margin-bottom: 10px">
                                                <el-card :body-style="{ padding: '0px' }">
                                                    <img :src="item.img" style="width:100%;height:85px" alt="">
                                                    <div style="padding: 14px;">
                                                        <span>{{item.title}}</span>
                                                        <el-button @click="select(item)" style="float: right; padding: 3px 0" type="text" class="button">选 择</el-button>
                                                    </div>
                                                </el-card>
                                            </el-col>
                                        </el-row>
                                        <el-button type="primary" slot="reference">选择背景图</el-button>
                                    </el-popover>
                                    <el-button class="button">{{backimgsTile}}</el-button>
                                </el-form-item>
                                <el-form-item v-if="user.id === 1" prop="hot" style="float: left;margin-right: 5px;">
                                    <el-checkbox v-model="hot" label="热门" @change="checkedHot" border></el-checkbox>
                                </el-form-item>
                                <el-form-item prop="lock">
                                    <el-checkbox v-model="lock" label="锁定" @change="checkedLock" border></el-checkbox>
                                </el-form-item>
                                <el-form-item required prop="thumb">
                                    <el-row :gutter="20">
                                        <el-col :span="24" style="padding-left: 5px;">
                                            <el-form-item required label="封面图：" prop="thumb">
                                                <el-upload
                                                        class="index-avatar-uploader"
                                                        :action="upload"
                                                        :headers="myHeaders"
                                                        :show-file-list="false"
                                                        name="pic"
                                                        :on-success="handleAvatarSuccess"
                                                        :before-upload="beforeAvatarUpload">
                                                    <img v-if="formData.thumb" :src="formData.thumb" class="index-avatar">
                                                    <i v-else class="el-icon-plus index-avatar-uploader-icon"></i>
                                                </el-upload>

                                            </el-form-item>
                                        </el-col>
                                        <el-col :span="24" style="margin-top:10px;">
                                            <el-tag type="danger" style="margin-bottom:10px;">上传封面图片格式只能是 JPG | PNG | GIF</el-tag>
                                            <el-tag type="danger" style="margin-bottom:10px;">上传封面图片大小不能超过 100KB!</el-tag>
                                            <el-tag type="danger" style="margin-bottom:10px;">上传的封面图宽高必须是 360*288 px !</el-tag>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item required  prop="title">
                                    <el-input style="width: 60%;top:-15px" v-bind:content="formData.title" v-model="formData.title" placeholder="请填写标题"></el-input>
                                    <el-color-picker
                                            v-model="formData.title_color"
                                            :predefine="predefineColors">
                                    </el-color-picker>
                                </el-form-item>
                                <el-form-item required prop="content">
                                    <editor-bar style="position: relative;top:-15px" v-on:catchData="catchData" v-bind:initData="formData.content"></editor-bar>
                                </el-form-item>
                                <el-form-item>
                                    <el-button style="float: right" type="primary" @click="update('formData')">保 存</el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <div class="preview-art">
                                    <div class="phone-content" :style="{'background':formData.backimg ? 'url('+ formData.backimg +')' : '#fff'}">
                                        <div class="phone-content-title"></div>
                                        <div ref="mobile" style="height: 550px;overflow: hidden;overflow-y:scroll;" v-html="formData.content"></div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div style="position: fixed;bottom:85px;right:15px"><el-button type="primary" @click="goback()">返回列表</el-button></div>
                </div>
            </section>
        </el-main>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {BackAll, ArticleUpdate ,ArticleInfo} from '../../utils/axios';
    import { VueCropper }  from 'vue-cropper';
    //富文本文件引入
    import EditorBar from '../layout/wangeditor';
    export default {
        components: {vBreadcrumb,VueCropper,EditorBar},
        data() {
            return {
                isClear: false,
                backimgs: [],//所有背景图
                backimgsShow:false,
                predefineColors: [
                    '#000000',
                    '#FF0000',
                    '#FFFFFF',
                    '#FFFF00',
                    '#00FF00',
                    '#0000FF',
                    '#9F00FF',
                ],
                backimgsTile:'暂未选择',
                breadcumb: [{name: "文章管理"},{name: "更新文章"}],
                formData:{
                    id:0,
                    title:'',
                    cateid:'',
                    thumb:'',
                    content:'',
                    backimg:'',
                    music:'',
                    title_color:'#000000',
                    music_name:'',
                    hot:0,
                    lock:0,
                },
                rules: {
                    title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
                    thumb: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
                    backimg: [{ required: true, message: '请选择背景图', trigger: 'blur' }],
                    music: [{ required: true, message: '请填写音乐名称', trigger: 'blur' }],
                    music_name: [{ required: true, message: '请填写音乐编号', trigger: 'blur' }],
                },
                previews: {},
                options: {
                    size: 1,
                    full: false,
                    info:true,
                    outputType: 'png',
                    canMove: true,
                    fixedBox: true,
                    autoCrop: true,
                    autoCropWidth: 375,
                    autoCropHeight: 300,
                    original: true,
                    canMoveBox: true
                },
                myHeaders:{
                    'Authorization': 'Bearer ' + this.$storage.get('token'),
                    'Accept': 'application/json'
                },
                hot:false,
                lock:false
            }
        },
        activated() {
            this.$store.dispatch('setActive', '/article');
            this.backimgsTile = '暂未选择';
            this.resetForm('formData');
            this.previews =  {};
            this.formData.content = '';
            this.formData = {
                id:0,
                title:'',
                thumb:'',
                cateid:'',
                content:'',
                title_color:'#000000',
                backimg:'',
                music:'',
                music_name:'',
                hot:0,
                lock:0,
            };
            this.backList(this.$route.params.id);
        },
        computed: {
            ...mapGetters(['active', 'mainHeight', 'loading', 'upload','user']),
        },
        methods: {
            catchData(val){
                this.formData.content = val;
            },
            select(backimg){
                this.backimgsTile = backimg.title;
                this.formData.backimg = backimg.img;
                this.backimgsShow = false;
            },
            checkedHot(){
                (this.formData.hot === 1)?this.formData.hot = 0:this.formData.hot = 1;
            },
            checkedLock(){
                (this.formData.lock === 1)?this.formData.lock = 0:this.formData.lock = 1;
            },
            backList(id){
                BackAll().then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.backimgs = response.data;
                        if(id){
                            ArticleInfo({params:{id:this.$route.params.id}}).then((res)=>{
                                if (response.code) {
                                    this.$message.error(response.msg);
                                } else {
                                    this.formData = {
                                        id:res.data.id,
                                        title:res.data.title,
                                        thumb:res.data.thumb,
                                        cateid:res.data.cateid,
                                        title_color: res.data.title_color,
                                        content:res.data.content,
                                        backimg:res.data.backimg,
                                        music:res.data.music,
                                        music_name:res.data.music_name,
                                        hot:res.data.hot,
                                        lock:res.data.lock,
                                    };
                                }
                                this.formData.content = res.data.content;
                                if(this.formData.hot === 1){
                                    this.hot = true;
                                }else {
                                    this.hot = false;
                                }
                                if(this.formData.lock === 1){
                                    this.lock = true;
                                }else {
                                    this.lock = false;
                                }
                                this.backimgs.filter((back)=>{
                                    if(back.img == res.data.backimg){
                                        this.backimgsTile = back.title;
                                    }
                                })
                            });
                        }
                    }
                })
            },
            realTime (data) {
                this.previews = data
            },
            uploadImg (e) {
                var file = e.target.files[0];
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(e.target.value)) {
                    this.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种');
                    return false;
                }
                var reader = new FileReader();
                reader.onload = (e) => {
                    let data;
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result;
                    }
                    this.formData.thumb = data;
                }
                // 转化为blob
                reader.readAsArrayBuffer(file);
            },
            goback(){
                this.$router.push({name:'Article'})
            },
            finish(){
                let formData = new FormData();
                this.$refs.cropper.getCropBlob((data) => {
                    formData.append("pic", data, this.formData.thumb);
                    this.$axios.post(this.upload, formData).then((response)=>{
                        this.formData.thumb = response.data.data;
                    });
                })
            },
            //更新
            update(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if(this.formData.thumb.indexOf('blob:') != -1){
                            this.$message.error('请上传封面图片');
                            return false;
                        }
                        if(!this.formData.content){
                            this.$message.error('请填写文章内容');
                            return false;
                        }
                        if(this.$refs.mobile.scrollHeight < 8700){
                            this.$message.error('文章内容长度太短，当前页面高度:'+this.$refs.mobile.scrollHeight+',规定页面最低高度为：8700');
                            return false;
                        }
                        ArticleUpdate(this.formData).then((response) => {
                            if (response.code) {
                                this.$message.error(response.msg);
                            } else {
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose: () => {
                                        this.$router.push({name:'Article'})
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //上传封面
            handleAvatarSuccess(res, file) {
                this.formData.thumb = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
                const isLt2M = file.size / 1024  < 100;
                if (!isJPG) {
                    this.$message.error('上传封面图片只能是 JPG | PNG | GIF格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传封面图片大小不能超过 100KB!');
                }
                let width = 360;
                let height = 288;
                const isSize = new Promise(function(resolve, reject) {
                    let _URL = window.URL || window.webkitURL;
                    let img = new Image();
                    img.onload = function() {
                        let valid = img.width === width && img.height === height;
                        valid ? resolve() : reject();
                    };
                    img.src = _URL.createObjectURL(file);
                }).then(() => {
                    return file;
                }, () => {
                    this.$message.error('上传的封面图宽高必须是'+width + '*'+ height+' PX !');
                    return Promise.reject();
                });
                return isJPG && isLt2M && isSize;
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            },
        },
    }
</script>
<style>
    .backimgs{
        max-height: 550px;overflow:hidden;overflow-y:scroll;
    }

</style>
